//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.jiaai.cloud.base.exception;

import com.jiaai.cloud.base.util.RestResult;
import com.jiaai.cloud.base.util.RestResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class RestExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);

    public RestExceptionHandler() {
    }

    @ExceptionHandler({ServiceException.class})
    @ResponseBody
    private <T> RestResult<T> serviceExceptionHandler(ServiceException e) {
        LOGGER.error("服务器内部异常 ---[msg]:{}---[description]:{}", e.getMessage(), e.getDescription());
        return RestResultGenerator.genErrorResult(e.getCode(), e.getMessage(), e.getDescription());
    }

    @ExceptionHandler({PermissionException.class})
    @ResponseBody
    private <T> RestResult<T> permissionExceptioHandler(PermissionException e) {
        LOGGER.error("没有权限 ---[msg]:{}---[description]:{}", e.getMessage(), e.getDescription());
        return RestResultGenerator.genErrorResult(e.getCode(), e.getMessage(), e.getDescription());
    }

    @ExceptionHandler({LoginException.class})
    @ResponseBody
    private <T> RestResult<T> loginExceptionHandler(LoginException e) {
        LOGGER.error("登录异常---[msg]:{}---[description]:{}", e.getMessage(), e.getDescription());
        return RestResultGenerator.genErrorResult(e.getCode(), e.getMessage(), e.getDescription());
    }

    @ExceptionHandler({Exception.class})
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("msg", e.getMessage());
        mav.setViewName("error");
        return mav;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private <T> RestResult<T> illegalParamsExceptionHandler(MethodArgumentNotValidException e) {
        return RestResultGenerator.genErrorResult(ErrorCode.ILLEGAL_PARAMS);
    }
}
